package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.hosp.repository.HosptialRepository;
import com.atguigu.yygh.hosp.service.HosptialService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HosptialServiceImpl implements HosptialService {

    @Autowired
    private HosptialRepository hosptialRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> paramMap) {

        //map集合转换成hosptial对象(1.map集合用JSONObject转换成字符串 2.字符串用JSONObject转换成目标对象)
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);

        //判断mongo中是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hosptialRepository.getHospitalByHoscode(hoscode);

        //存在则更新（mongo中添加相同主键的数据会视为更新）
        if(hospitalExist != null){
            hospital.setStatus(hospitalExist.getStatus());   //继承库中原数据状态
            hospital.setCreateTime(hospitalExist.getCreateTime());  //继承库中原数据创建时间
            hospital.setUpdateTime(new Date());  //更新新数据更新时间
            hospital.setIsDeleted(0);
            hosptialRepository.save(hospital);  //更新成新数据

        }else{
            //不存在则添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hosptialRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hosptialRepository.getHospitalByHoscode(hoscode);
    }

    @Override
    public Page selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //mongoDB的Repository分页查询过程，需熟练掌握
        //创建pageable对象
        Pageable pageable = PageRequest.of(page-1,limit);
        //创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);  //忽略大小写
        //hospitalQueryVo转换成hospital
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //创建Example对象
        Example<Hospital> example = Example.of(hospital,matcher);
        //调用方法
        Page<Hospital> pages = hosptialRepository.findAll(example, pageable);
        //List<Hospital> content = pages.getContent();

        //Hospital的pojo类中可以看到并没有医院等级属性，其父类BaseMongoEntity中也没有，但是BaseMongoEntity有param其他参数的map，我们可以把
        //医院等级放置到此map中，需要的时候根据key来获取

        //获取查询得到的list集合，遍历进行医院等级封装(java8里的stream流式遍历)
        pages.getContent().stream().forEach(item ->{
            this.setHosptialHosType(item);
        });

        return pages;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        //根据id查询医院信息
        Hospital hospital = hosptialRepository.findById(id).get();
        //设置修改值
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hosptialRepository.save(hospital);
    }

    @Override
    public Map<String,Object> getHospDetailById(String id) {
        //包含医院的基本信息以及医院的等级信息
        Hospital hospital = this.setHosptialHosType(hosptialRepository.findById(id).get());
        HashMap<String,Object> stringHospitalHashMap = new HashMap<>();
        stringHospitalHashMap.put("hospital",hospital);
        //单独处理更直观(预约信息)
        stringHospitalHashMap.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);

        return stringHospitalHashMap;
    }

    //获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hosptialRepository.getHospitalByHoscode(hoscode);
        if(hospital != null) {
            return hospital.getHosname();
        }
        return null;
    }

    //根据医院名称查询
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hosptialRepository.findHospitalByHosnameLike(hosname);
    }

    //根据医院编号获取医院预约挂号详情
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHosptialHosType(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //获取查询得到的list集合，遍历进行医院等级封装
    private Hospital setHosptialHosType(Hospital hospital) {  //这样在循环中执行查询数据库操作消耗太大，可不可以放入缓存中操作呢
        //根据dictCode和value获取医院等级名称
        String hosType = dictFeignClient.getName("HosType", hospital.getHostype()); //双参，dictcode是HosType，value是getHostype()
        //查询省，市，地区，同样封装到param里面
        String province = dictFeignClient.getName(hospital.getProvinceCode());
        String city = dictFeignClient.getName(hospital.getCityCode());
        String district = dictFeignClient.getName(hospital.getDistrictCode());
        hospital.getParam().put("HosType",hosType);
        hospital.getParam().put("fullAddress",province+city+district);
        return hospital;
    }
}
